// echo_server.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define PORT 7000  // 服务器端口
#define BUFFER_SIZE 1024
#define SERVER_PREFIX "server: "

int main() {
    int server_fd, client_fd;
    struct sockaddr_in address;
    int addrlen = sizeof(address);
    char buffer[BUFFER_SIZE];

    // 创建套接字
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }

    // 设置地址结构
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(PORT);

    // 绑定
    if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
        perror("bind failed");
        close(server_fd);
        exit(EXIT_FAILURE);
    }

    // 监听
    if (listen(server_fd, 3) < 0) {
        perror("listen");
        close(server_fd);
        exit(EXIT_FAILURE);
    }

    printf("Echo server listening on port %d ", PORT);

    while (1) {
        // 接受连接
        if ((client_fd = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
            perror("accept");
            close(server_fd);
            exit(EXIT_FAILURE);
        }

        // 清空缓冲区
        while (1) {  // 循环处理客户端的请求
            memset(buffer, 0, BUFFER_SIZE);

            // 接收数据
            ssize_t bytes_read = read(client_fd, buffer, BUFFER_SIZE);
            if (bytes_read <= 0) {
                printf("Client disconnected.  ");
                break;  // 客户端断开连接
            }
            printf("Received: \n%s", buffer);
            
            // 去掉 "client: " 前缀
            const char *client_prefix = "client: ";
            // 检查并去掉前缀
            if (strncmp(buffer, client_prefix, strlen(client_prefix)) == 0) {
                // 计算去掉前缀后的消息
                char response[BUFFER_SIZE];
                snprintf(response, BUFFER_SIZE, "%s%s", SERVER_PREFIX, buffer + strlen(client_prefix));
                send(client_fd, response, strlen(response), 0);
            }
        }

        // 关闭客户端连接
        close(client_fd);
    }

    // 关闭服务器套接字（这部分实际上不会到达因为是无限循环）
    close(server_fd);
    return 0;
}

